// 鱼泡直聘

// ------------- 获取简历DOM元素 -------------
export const getResumeDOM = () => {
	try {
		const currentName = getCurrentCandidateName();
		if (!currentName) {
			return '未找到简历容器元素';
		}
		console.log('开始获取简历DOM元素...');

		// ------------- 获取容器位置 -------------
		const innerBoxList = document.querySelectorAll('[class*="_innerbox_"]');
		console.log('找到的innerBoxList数量:', innerBoxList.length);

		if (innerBoxList.length === 0) {
			return '未找到简历容器元素';
		}
		// 选择带有候选人姓名的innerBox作为简历容器
		let resumeContainer = null;
		for (let i = innerBoxList.length - 1; i >= 0; i--) {
			const box = innerBoxList[i];
			const nameElement = box.querySelector('[class*="username"]');
			const name = nameElement?.textContent?.trim() || '';
			console.log('当前innerBox姓名:', name);
			console.log(`${name == currentName}, ${name}, ${currentName}`);

			if (name == currentName) {
				resumeContainer = box;
				break;
			}
		}
		if (!resumeContainer) {
			return '未找到简历容器元素';
		}

		console.log('简历容器:', resumeContainer);

		// ------------- 获取基本信息 -------------
		/** 用户信息容器 */
		const userInfoContainer = resumeContainer.querySelector('[class*="_avatarR_"]');
		// ----- 获取头像 -----
		const avatar = userInfoContainer?.children[0]?.getElementsByTagName('img')[0]?.src ?? '';
		// ----- 获取姓名 -----
		/** 用户信息文本容器（不带头像） */
		const userInfoTextContainer = userInfoContainer.children[1];
		const name = userInfoTextContainer.querySelector('[class*="username"]').textContent ?? '';
		// ----- 获取性别 -----
		const sexImageUrl = userInfoTextContainer.getElementsByTagName('img')[0]?.src ?? '';
		const sex = sexImageUrl.includes('sex_male') ? '男' : sexImageUrl.includes('sex_female') ? '女' : '';
		// ----- 获取年龄、学历、经验、在职状态 -----
		/** 基本信息容器 */
		const baseInfoContainer = userInfoTextContainer.querySelector('[class*="baseInfo"]');
		// 基本信息数量不定，可能有空缺
		let age = ''; // 年龄
		let degree = ''; // 学历
		let experience = ''; // X年经验，这项可能没有
		let workStatus = ''; // 在职状态（离职、在职），这项可能没有
		// let nation = ''; // 民族
		if (baseInfoContainer.children.length == 5) {
			// 信息完全
			age = baseInfoContainer.children[0].textContent ?? '';
			// 不记录民族数据
			degree = baseInfoContainer.children[2].textContent ?? '';
			experience = baseInfoContainer.children[3].textContent ?? '';
			workStatus = baseInfoContainer.children[4].textContent ?? '';
		}
		if (baseInfoContainer.children.length == 4) {
			// 信息完全
			age = baseInfoContainer.children[0].textContent ?? '';
			degree = baseInfoContainer.children[1].textContent ?? '';
			experience = baseInfoContainer.children[2].textContent ?? '';
			workStatus = baseInfoContainer.children[3].textContent ?? '';
		} else if (baseInfoContainer.children.length == 3) {
			// 信息缺失，可能是经验或在职状态
			age = baseInfoContainer.children[0].textContent ?? '';
			degree = baseInfoContainer.children[1].textContent ?? '';
			if (baseInfoContainer.children[2].textContent.includes('经验')) {
				experience = baseInfoContainer.children[2].textContent ?? '无经验';
			} else {
				workStatus = baseInfoContainer.children[2].textContent ?? '无工作';
			}
		} else if (baseInfoContainer.children.length == 2) {
			// 信息缺失，可能是经验或在职状态
			age = baseInfoContainer.children[0].textContent ?? '';
			degree = baseInfoContainer.children[1].textContent ?? '';
		}
		// ----- 获取基本介绍 -----
		/** 基本介绍容器 */
		const introduction = userInfoTextContainer.querySelector('[class*="introduce"]')?.textContent ?? '';

		/** 基本信息 */
		const baseInfo = {
			name, // 姓名
			age, // 年龄
			sex, // 性别
			avatar, // 头像
			experience, // 经验
			workStatus, // 在职状态
			highestSchool: '', // 最高学历学校
			degree, // 学历
			introduction, // 基本介绍
			currentCompany: '' // 目前在职公司
		};

		// ------------- 获取期望信息 -------------
		// 所有信息容器
		const allInfoContainer = resumeContainer.querySelectorAll('[class*="titleR"]');
		// 通过标题选择器，获取对应容器
		const selectWrapperByTitle = (wrapperList, keyword) => {
			for (let i = 0; i < wrapperList.length; i++) {
				const wrapper = wrapperList[i];
				const title = wrapper.querySelector('[class*="title"]')?.textContent ?? '';
				if (title.includes(keyword)) {
					return wrapper;
				}
			}
			return null;
		};
		/** 期望信息容器 */
		const expectInfoContainer = selectWrapperByTitle(allInfoContainer, '期望职位');
		/** 期望信息 */
		let expectInfo = {
			expectJob: '', // 期望岗位
			expectSalary: '', // 期望薪资
			expectCity: '' // 期望城市
		};
		if (expectInfoContainer) {
			// ----- 获取期望岗位 -----
			expectInfo.expectJob = expectInfoContainer?.querySelector('[class*="hopeJobName"]')?.textContent ?? '';
			// ----- 获取期望薪资 -----
			expectInfo.expectSalary = expectInfoContainer?.querySelector('[class*="hopeJobSalary"]')?.textContent ?? ''; // 期望薪资
			// ----- 获取期望城市 -----
			const workCityContainer = selectWrapperByTitle(allInfoContainer, '工作城市');
			// ----- 获取期望城市 -----
			if (workCityContainer) {
				expectInfo.expectCity = workCityContainer?.querySelector('[class*="hopeJobCity"]')?.textContent ?? ''; // 期望城市
			}
		} else {
			expectInfo = {};
		}

		// ------------- 获取工作经历 -------------
		const workExperienceContainer = selectWrapperByTitle(allInfoContainer, '工作经历');
		/** 工作经历列表 */
		let workExperienceList = [];
		if (workExperienceContainer) {
			// ----- 获取工作经历容器 -----
			const workExperienceWrapperList = workExperienceContainer?.querySelectorAll('[class*="workExItem"]'); // 工作经历

			for (let i = 0; i < workExperienceWrapperList.length; i++) {
				const workExperienceWrapper = workExperienceWrapperList[i];
				const companyName = workExperienceWrapper?.querySelector('[class*="coName"]')?.textContent ?? ''; // 公司名称
				const workPost = workExperienceWrapper?.querySelector('[class*="jobName"]')?.textContent ?? ''; // 岗位名称
				const workTime = workExperienceWrapper?.querySelector('[class*="workDate"]')?.textContent ?? ''; // 工作时间
				const workDescList = workExperienceWrapper?.querySelectorAll('[class*="workContentI"]'); // 工作描述
				let workDesc = ''; // 工作描述
				for (let j = 0; j < workDescList.length; j++) {
					const workDescItem = workDescList[j];
					workDesc += workDescItem?.textContent + '\n' ?? '';
				}
				workExperienceList.push({
					companyName,
					workPost,
					workTime,
					workDesc
				});
			}
			baseInfo.currentCompany = workExperienceList[0]?.companyName || '';
		}

		// ------------- 获取项目经历 -------------
		const projectExperienceContainer = selectWrapperByTitle(allInfoContainer, '项目经历');
		/** 项目经历列表 */
		let projectExperienceList = [];
		if (projectExperienceContainer) {
			// ----- 获取项目经历容器 -----
			const projectExperienceWrapperList = projectExperienceContainer?.querySelectorAll('[class*="projectItem"]'); // 项目经历

			for (let i = 0; i < projectExperienceWrapperList.length; i++) {
				const projectExperienceWrapper = projectExperienceWrapperList[i];
				const projectName = projectExperienceWrapper?.querySelector('[class*="projectTitle"]')?.textContent ?? ''; // 项目名称
				const projectPost = projectExperienceWrapper?.querySelector('[class*="projectRole"]')?.textContent ?? ''; // 岗位名称
				const projectTime = projectExperienceWrapper?.querySelector('[class*="projectTime"]')?.textContent ?? ''; // 项目时间
				const projectDescList = projectExperienceWrapper?.querySelectorAll('[class*="projectDesc"]'); // 项目描述
				let projectDesc = ''; // 项目描述
				for (let j = 0; j < projectDescList.length; j++) {
					const projectDescItem = projectDescList[j];
					projectDesc += projectDescItem?.textContent + '\n' ?? '';
				}
				projectExperienceList.push({
					projectName,
					projectPost,
					projectTime,
					projectDesc
				});
			}
		}

		// ------------- 获取教育经历 -------------
		const educationExperienceContainer = selectWrapperByTitle(allInfoContainer, '教育经历');
		/** 教育经历列表 */
		let educationExperienceList = [];
		if (educationExperienceContainer) {
			// ----- 获取教育经历容器 -----
			const educationExperienceWrapperList = educationExperienceContainer?.querySelectorAll('[class*="eduItem"]'); // 教育经历
			for (let i = 0; i < educationExperienceWrapperList.length; i++) {
				const educationExperienceWrapper = educationExperienceWrapperList[i];
				const educationNameWrapper = educationExperienceWrapper?.querySelector('[class*="eduNameR"]'); // 学校名称容器
				const schoolName = educationNameWrapper?.children[0].children[0].textContent ?? ''; // 学校名称
				const schoolTagListWrapperList = educationNameWrapper?.querySelectorAll('[class*="majorTag"]'); // 专业标签容器
				/** 专业标签列表 */
				let schoolTagList = [];
				for (let j = 0; j < schoolTagListWrapperList.length; j++) {
					const schoolTag = schoolTagListWrapperList[j]?.textContent ?? '';
					schoolTagList.push(schoolTag);
				}
				const schoolDesc = educationExperienceWrapper.querySelector('[class*="eduBaseInfo"]')?.textContent;
				const schoolMajor = schoolDesc.split(' · ')[0]; // 专业
				const schoolDegree = schoolDesc.split(' · ')[2]; // 学历
				const schoolTime = educationExperienceWrapper?.querySelector('[class*="eduDate"]')?.textContent ?? ''; // 教育时间
				educationExperienceList.push({
					schoolName,
					schoolTagList,
					schoolDegree,
					schoolTime,
					schoolDesc,
					schoolMajor
				});
			}
			baseInfo.highestSchool = educationExperienceList[0]?.schoolName || '';
		}

		/** 完整简历信息 */
		const resume = {
			baseInfo,
			expectInfo,
			workExperienceList,
			projectExperienceList,
			educationExperienceList
		};

		console.log('完整的简历数据:', resume);
		return resume;
	} catch (error) {
		console.error('获取简历DOM时出错:', error);
		return null;
	}
};

// ------------- 获取当前候选人姓名 -------------
export const getCurrentCandidateName = () => {
	const conversationContainer = document.querySelector('[class*="chat-conversation"]');
	const userInfoContainer = conversationContainer?.querySelector('[class*="user-info"]');
	const nameElement = userInfoContainer?.querySelector('[class*="name"]')?.textContent ?? '';
	console.log('当前候选人姓名:', nameElement);
	return nameElement;
};

// ------------- 设置快捷回复到输入框 -------------
export const setQuickTalkIntoInput = (text) => {
	const inputContainer = document.querySelector('[class*="fb-editor-container"]');
	if (!inputContainer) {
		console.error('没有打开与候选人的沟通界面！');
		return;
	}
	const inputElement = inputContainer.querySelector('.fb-editor')?.children[0];
	if (inputElement) {
		inputElement.textContent = text;
	}
};

// ------------- 字段转换 -------------
// 将简历字段转化成满天星平台接口字段
export const convertResumeFields = (resume) => {
    const { baseInfo, expectInfo, workExperienceList, projectExperienceList, educationExperienceList } = resume;

    // 处理基本信息
    const candidateName = baseInfo.name || '';
    const phone = ''; // 原数据中没有联系方式字段
    const email = ''; // 原数据中没有邮箱字段
    const avatar = baseInfo.avatar || '';
    const sex = baseInfo.sex === '男' ? 1 : (baseInfo.sex === '女' ? 2 : 0); // 转换性别为数字
    const ages = parseInt(baseInfo.age) || 0;
    
    // 处理教育信息
    let educationBackground = '';
    
    if (educationExperienceList && educationExperienceList.length > 0) {
        educationBackground = baseInfo.highestSchool || '';
    }
    
    const selfEvaluation = baseInfo.introduction || '';
    const professionalSkill = ''; // 原数据中没有技能字段
    
    // 处理工作经历
    const workExperienceListFormatted = workExperienceList ? workExperienceList.map(work => {
        // 处理工作时间，格式为 "YYYY-MM"
        let startDate = '';
        let endDate = '';
        
        if (work.workTime) {
            const timeParts = work.workTime.split('-');
            if (timeParts.length >= 1) {
                startDate = timeParts[0].trim();
            }
            if (timeParts.length >= 2) {
                endDate = timeParts[1].trim();
            }
        }
        
        return {
            workExperienceId: 0,
            submitCandidateId: 0,
            company: work.companyName || '',
            postName: work.workPost || '',
            description: work.workDesc || '',
            startDate,
            endDate,
            label: '',
            createdBy: '',
            gmtCreate: '',
            updatedBy: '',
            gmtModify: ''
        };
    }) : [];
    
    // 处理期望信息
    let minSalary = 0;
    let maxSalary = 0;
    let expectCity = '';
    let expectPost = '';
    
    if (expectInfo) {
        // 处理期望薪资
        if (expectInfo.expectSalary) {
            const salaryStr = expectInfo.expectSalary;
            // 匹配薪资范围，例如 "8K-10K" 或 "8-10K"
            const salaryMatch = salaryStr.match(/(\d+)-(\d+)K/);
            if (salaryMatch) {
                minSalary = parseInt(salaryMatch[1]) * 1000;
                maxSalary = parseInt(salaryMatch[2]) * 1000;
            } else {
                // 匹配单个薪资值，例如 "8K"
                const singleSalaryMatch = salaryStr.match(/(\d+)K/);
                if (singleSalaryMatch) {
                    minSalary = parseInt(singleSalaryMatch[1]) * 1000;
                    maxSalary = parseInt(singleSalaryMatch[1]) * 1000;
                }
            }
        }
        
        expectCity = expectInfo.expectCity || '';
        expectPost = expectInfo.expectJob || '';
    }
    
    // 处理工作年限
    let workYears = '0';
    if (baseInfo.experience) {
        // 匹配工作年限，例如 "2年经验"
        const yearMatch = baseInfo.experience.match(/(\d+)年/);
        if (yearMatch) {
            workYears = yearMatch[1];
        }
    }
    
    // 处理教育经历
    const educationExperienceListFormatted = educationExperienceList ? educationExperienceList.map(education => {
        // 处理教育时间，格式为 "YYYY-MM"
        let startDate = '';
        let endDate = '';
        
        if (education.schoolTime) {
            const timeParts = education.schoolTime.split('-');
            if (timeParts.length >= 1) {
                startDate = timeParts[0].trim();
                // 替换斜杠为横杠
                startDate = startDate.replace(/\//g, '-');
            }
            if (timeParts.length >= 2) {
                endDate = timeParts[1].trim();
                // 替换斜杠为横杠
                endDate = endDate.replace(/\//g, '-');
            }
        }
        
        return {
            educationExperienceId: 0,
            submitCandidateId: 0,
            school: education.schoolName || '',
            profession: education.schoolMajor || '',
            educationBackground: education.schoolDegree || '',
            startDate,
            endDate,
            label: '',
            createdBy: '',
            gmtCreate: '',
            updatedBy: '',
            gmtModify: ''
        };
    }) : [];
    
    // 处理项目经历
    const projectExperienceListFormatted = projectExperienceList ? projectExperienceList.map(project => {
        // 处理项目时间，格式为 "YYYY-MM"
        let startDate = '';
        let endDate = '';
        
        if (project.projectTime) {
            const timeParts = project.projectTime.split('-');
            if (timeParts.length >= 1) {
                startDate = timeParts[0].trim();
                // 替换斜杠为横杠
                startDate = startDate.replace(/\//g, '-');
            }
            if (timeParts.length >= 2) {
                endDate = timeParts[1].trim();
                // 替换斜杠为横杠
                endDate = endDate.replace(/\//g, '-');
            }
        }
        
        return {
            projectExperienceId: 0,
            submitCandidateId: 0,
            project: project.projectName || '',
            description: `项目描述: ${project.projectDesc}\n责任描述: ${project.projectPost}`,
            startDate,
            endDate,
            label: '',
            createdBy: '',
            gmtCreate: '',
            updatedBy: '',
            gmtModify: ''
        };
    }) : [];
    
    // 返回转换后的数据
    return {
        recruitDemandId: 0,
        submitCandidateId: 0,
        candidateName,
        phone,
        email,
        submitClaimId: 0,
        candidateId: 0,
        reportUserId: '',
        post: expectPost,
        attachments: '',
        avatar,
        sex,
        status: 0,
        entryDeptId: '',
        reportDeptConfigId: '',
        remark: '',
        escapeDate: 0,
        releaseDate: '',
        createdBy: '',
        createdTime: '',
        updatedBy: '',
        updatedTime: '',
        educationBackground,
        workYears,
        ages,
        expectCity,
        expectPost,
        minSalary,
        maxSalary,
        selfEvaluation,
        professionalSkill,
        educationExperienceList: educationExperienceListFormatted,
        workExperienceList: workExperienceListFormatted,
        projectExperienceList: projectExperienceListFormatted
    };
};
